package com.qh.basic.interceptor;

import com.qh.basic.jwt.JwtUtils;
import com.qh.basic.jwt.LoginData;
import com.qh.basic.jwt.RsaUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取token
        String token = request.getHeader("token");
        //再去重redis获取登录信息
        if (token != null){
            try {
                //1.获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().
                        getResource("auth_rsa.pub").getFile());
                //解密
                JwtUtils.getInfoFromToken(token,publicKey, LoginData.class);
                //问题：没有刷新过期时间
                return true;
            } catch (ExpiredJwtException e) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println("{\"success\":false,\"msg\":\"timeout\"}");
                return false;
            }

        }
        //没有登录，或者是登录信息过期。
        //token为null，或者是登录信息logininfo过期
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");
        return false;
    }
}
